package basic.arch.component.lock.distributed.zookeeper;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import basic.arch.component.lock.aop.annotation.Lock.DisstributionLockType;
import basic.arch.component.lock.config.CurrentLockSettings;
import basic.arch.component.lock.distributed.DistributionLockSupport;

@Component("zookeeperDistributionLock")
public class ZookeeperDistributionLock extends DistributionLockSupport{
   
    @Value("${lock.zk.expire}")
    private long expire = 60000;
    private static final ThreadLocal<InterProcessMutex> threadLocal = new ThreadLocal<InterProcessMutex>();

    @Override
    public boolean tryLock(CurrentLockSettings currentLockSettings) {
        InterProcessMutex lock = new InterProcessMutex(ZkClientService.client,ZkClientService.ROOT+"/"+ currentLockSettings.getCurrenLockKey());
        threadLocal.set(lock);
        return super.tryLock(currentLockSettings);
    }
    
    @Override
    protected boolean acquire(CurrentLockSettings currentLockSettings) throws Exception {
        return threadLocal.get().acquire(expire, TimeUnit.MILLISECONDS);
    }

    @Override
    protected void unlock0(String key) {
        try {
            InterProcessMutex lock = threadLocal.get();
            lock.release();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(),e);
        }finally {
            threadLocal.remove();
        }
    }

    @Override
    public DisstributionLockType getType() {
        return DisstributionLockType.ZOOKEEPER;
    }
}
